"""
默认配置模块

提供系统的默认配置，包括主配置、验证配置和TL配比配置。
当配置文件不存在时，系统会使用这些默认值。
"""

from typing import Dict, Any, List


def get_default_main_config() -> Dict[str, Any]:
    """
    获取默认主配置
    
    Returns:
        Dict[str, Any]: 包含完整应用程序配置的字典
    """
    return {
        # 数据源配置
        "data_sources": {
            "projects_file": "data/input/projects.xlsx",
            "resources_file": "data/input/resources.xlsx", 
            "tasks_file": "data/input/tasks.xlsx"
        },
        
        # 输出配置
        "output": {
            "directory": "data/output",
            "template_file": "Template/【公開用】PM_要員計画（山積み表・リソースヒストグラム）_20211121_01.xlsx",
            "filename_pattern": "【公開用】PM_要員計画（山積み表・リソースヒストグラム）_{date}_{version}.xlsx"
        },
        
        # 算法参数配置
        "algorithm": {
            "time_unit": "month",  # week/month
            "max_iterations": 100,
            "optimization_target": "duration",  # duration/utilization/balance
            
            # 资源分配策略
            "allocation_strategy": {
                "prefer_skill_match": True,
                "allow_overtime": False,
                "max_workload_percentage": 100
            },
            
            # 冲突解决策略
            "conflict_resolution": {
                "auto_adjust_dates": True,
                "priority_based": True,
                "show_warnings": True
            }
        },
        
        # 显示设置
        "display": {
            "date_format": "%Y-%m-%d",
            "currency": "JPY",
            "language": "jp",
            
            # Excel格式设置
            "excel_format": {
                "header_style": "bold",
                "date_format": "yyyy-mm-dd",
                "number_format": "#,##0"
            }
        },
        
        # 验证规则（基础配置，详细配置在validation_config.yaml中）
        "validation": {
            "required_fields": {
                "projects": ["project_id", "project_name", "start_date", "end_date"],
                "resources": ["resource_id", "name", "role", "max_hours_per_week"],
                "tasks": ["task_id", "project_id", "task_name", "estimated_hours"]
            },
            
            "data_constraints": {
                "max_project_duration_months": 24,
                "min_skill_level": 1,
                "max_skill_level": 5,
                "max_hours_per_week": 60
            }
        },
        
        # 日志设置
        "logging": {
            "level": "INFO",  # DEBUG/INFO/WARNING/ERROR
            "file": "logs/auto_resource_plan.log",
            "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
        }
    }


def get_default_validation_config() -> Dict[str, Any]:
    """
    获取默认验证配置
    
    Returns:
        Dict[str, Any]: 包含所有数据验证规则的字典
    """
    return {
        # 项目数据验证规则
        "projects": {
            # 必需字段
            "required_fields": [
                "project_id", "project_name", "start_date", "end_date", 
                "priority", "status", "description"
            ],
            
            # 字段验证规则
            "field_validations": {
                "project_id": {
                    "type": "string",
                    "max_length": 20,
                    "pattern": r"^[A-Z0-9_-]+$"
                },
                "project_name": {
                    "type": "string",
                    "max_length": 100,
                    "min_length": 1
                },
                "start_date": {
                    "type": "date",
                    "format": "%Y-%m-%d"
                },
                "end_date": {
                    "type": "date", 
                    "format": "%Y-%m-%d"
                },
                "priority": {
                    "type": "integer",
                    "min_value": 1,
                    "max_value": 5
                },
                "status": {
                    "type": "string",
                    "allowed_values": ["计划中", "进行中", "已完成", "已取消", "暂停"]
                }
            },
            
            # 业务逻辑验证
            "business_rules": [
                {
                    "name": "end_date_after_start_date",
                    "description": "结束日期必须晚于开始日期",
                    "validation": "end_date > start_date"
                },
                {
                    "name": "project_duration_limit",
                    "description": "项目持续时间不能超过24个月",
                    "validation": "months_between(start_date, end_date) <= 24"
                }
            ]
        },
        
        # 资源数据验证规则
        "resources": {
            # 必需字段
            "required_fields": [
                "resource_id", "name", "role", "skill_level", 
                "max_hours_per_week", "cost_per_hour", "available_start_date"
            ],
            
            # 字段验证规则
            "field_validations": {
                "resource_id": {
                    "type": "string",
                    "max_length": 20,
                    "pattern": r"^[A-Z0-9_-]+$"
                },
                "name": {
                    "type": "string",
                    "max_length": 50,
                    "min_length": 1
                },
                "role": {
                    "type": "string",
                    "allowed_values": [
                        "PM", "PL", "SE", "PG", "テスター", "デザイナー", 
                        "インフラ", "DBA", "アーキテクト", "コンサルタント"
                    ]
                },
                "skill_level": {
                    "type": "integer",
                    "min_value": 1,
                    "max_value": 5
                },
                "max_hours_per_week": {
                    "type": "integer",
                    "min_value": 1,
                    "max_value": 60
                },
                "cost_per_hour": {
                    "type": "float",
                    "min_value": 0,
                    "max_value": 50000
                },
                "available_start_date": {
                    "type": "date",
                    "format": "%Y-%m-%d"
                }
            },
            
            # 业务逻辑验证
            "business_rules": [
                {
                    "name": "reasonable_hours_per_week",
                    "description": "每周工作小时数应在合理范围内",
                    "validation": "max_hours_per_week >= 20 and max_hours_per_week <= 40"
                }
            ]
        },
        
        # 任务数据验证规则
        "tasks": {
            # 必需字段
            "required_fields": [
                "task_id", "project_id", "task_name", "estimated_hours", 
                "required_role", "required_skill_level", "start_date", "end_date"
            ],
            
            # 字段验证规则
            "field_validations": {
                "task_id": {
                    "type": "string",
                    "max_length": 30,
                    "pattern": r"^[A-Z0-9_-]+$"
                },
                "project_id": {
                    "type": "string",
                    "max_length": 20,
                    "pattern": r"^[A-Z0-9_-]+$"
                },
                "task_name": {
                    "type": "string",
                    "max_length": 100,
                    "min_length": 1
                },
                "estimated_hours": {
                    "type": "integer",
                    "min_value": 1,
                    "max_value": 2000
                },
                "required_role": {
                    "type": "string",
                    "allowed_values": [
                        "PM", "PL", "SE", "PG", "テスター", "デザイナー", 
                        "インフラ", "DBA", "アーキテクト", "コンサルタント"
                    ]
                },
                "required_skill_level": {
                    "type": "integer",
                    "min_value": 1,
                    "max_value": 5
                },
                "start_date": {
                    "type": "date",
                    "format": "%Y-%m-%d"
                },
                "end_date": {
                    "type": "date",
                    "format": "%Y-%m-%d"
                }
            },
            
            # 业务逻辑验证
            "business_rules": [
                {
                    "name": "task_end_date_after_start_date",
                    "description": "任务结束日期必须晚于开始日期",
                    "validation": "end_date > start_date"
                },
                {
                    "name": "task_within_project_timeframe",
                    "description": "任务时间范围必须在项目时间范围内",
                    "validation": "task_dates_within_project_dates"
                },
                {
                    "name": "reasonable_estimated_hours",
                    "description": "预估工时应该合理",
                    "validation": "estimated_hours <= days_between(start_date, end_date) * 8"
                }
            ]
        },
        
        # 全局验证规则
        "global_validations": {
            # 数据一致性检查
            "data_consistency": [
                {
                    "name": "project_task_consistency",
                    "description": "所有任务的project_id必须在项目表中存在",
                    "validation": "all_task_project_ids_exist_in_projects"
                },
                {
                    "name": "resource_allocation_feasibility",
                    "description": "资源分配必须可行",
                    "validation": "resource_allocation_is_feasible"
                }
            ],
            
            # 数据质量检查
            "data_quality": [
                {
                    "name": "no_duplicate_ids",
                    "description": "ID字段不能有重复值",
                    "validation": "check_unique_ids"
                },
                {
                    "name": "complete_data",
                    "description": "关键数据不能缺失",
                    "validation": "check_data_completeness"
                }
            ]
        },
        
        # 验证配置
        "validation_settings": {
            "strict_mode": False,  # 严格模式：任何验证失败都会停止处理
            "auto_fix_minor_issues": True,  # 自动修复小问题
            "generate_validation_report": True,  # 生成验证报告
            "validation_report_path": "data/output/validation_report.xlsx"
        }
    }


def get_default_tl_ratio_config() -> Dict[str, Any]:
    """
    获取默认TL配比配置
    
    Returns:
        Dict[str, Any]: 包含TL配比规则的字典
    """
    return {
        # TL配比规则配置
        "tl_ratio_rules": {
            # 基础配比规则
            "base_rules": {
                "min_team_size_for_tl": 3,  # 最少3人团队需要TL
                "max_team_size_per_tl": 8,  # 每个TL最多管理8人
                "tl_to_member_ratio": 0.125,  # TL与成员的标准比例（1:8）
                "senior_member_can_be_tl": True  # 高级成员可以兼任TL
            },
            
            # 项目规模配比
            "project_scale_rules": [
                {
                    "project_size": "small",  # 小型项目
                    "team_size_range": [1, 5],
                    "tl_count": 0,  # 小项目不需要专门的TL
                    "can_use_senior_as_tl": True
                },
                {
                    "project_size": "medium",  # 中型项目
                    "team_size_range": [6, 15],
                    "tl_count": 1,
                    "can_use_senior_as_tl": True
                },
                {
                    "project_size": "large",  # 大型项目
                    "team_size_range": [16, 30],
                    "tl_count": 2,
                    "can_use_senior_as_tl": False  # 需要专门的TL
                },
                {
                    "project_size": "extra_large",  # 超大型项目
                    "team_size_range": [31, 100],
                    "tl_count": "calculated",  # 根据团队规模计算
                    "calculation_method": "team_size / 8",
                    "can_use_senior_as_tl": False
                }
            ]
        },
        
        # 角色别配比规则
        "role_based_rules": {
            # PM配比
            "pm_rules": {
                "max_projects_per_pm": 3,  # 每个PM最多管理3个项目
                "min_team_size_for_dedicated_pm": 5,  # 5人以上团队需要专门PM
                "pm_workload_percentage": 80  # PM工作量占比
            },
            
            # PL配比
            "pl_rules": {
                "max_team_size_per_pl": 6,  # 每个PL最多管理6人
                "min_team_size_for_pl": 4,  # 4人以上团队需要PL
                "pl_can_develop": True,  # PL可以兼做开发
                "pl_development_percentage": 30  # PL开发工作量占比
            },
            
            # SE配比
            "se_rules": {
                "se_to_pg_ratio": 0.5,  # SE与PG的比例（1:2）
                "min_se_count": 1,  # 最少1个SE
                "se_can_do_pg_work": True  # SE可以做PG工作
            },
            
            # 测试人员配比
            "tester_rules": {
                "tester_to_developer_ratio": 0.3,  # 测试人员与开发人员比例（1:3）
                "min_tester_count_for_medium_project": 1,
                "dedicated_tester_threshold": 10  # 10人以上项目需要专门测试人员
            }
        },
        
        # 技能水平配比
        "skill_level_rules": {
            # 技能水平分布
            "skill_distribution": {
                "level_5_percentage": 10,  # 专家级占比
                "level_4_percentage": 20,  # 高级占比
                "level_3_percentage": 40,  # 中级占比
                "level_2_percentage": 25,  # 初级占比
                "level_1_percentage": 5    # 新手占比
            },
            
            # 关键角色技能要求
            "critical_role_requirements": {
                "PM": {"min_skill_level": 4},
                "PL": {"min_skill_level": 4}, 
                "アーキテクト": {"min_skill_level": 5},
                "TL": {"min_skill_level": 3}
            }
        },
        
        # 动态调整规则
        "dynamic_adjustment": {
            # 项目阶段调整
            "phase_adjustments": {
                "planning": {
                    "pm_workload_multiplier": 1.5,
                    "architect_workload_multiplier": 2.0
                },
                "development": {
                    "se_pg_ratio_multiplier": 1.0,
                    "tester_ratio_multiplier": 0.5
                },
                "testing": {
                    "tester_ratio_multiplier": 2.0,
                    "se_workload_multiplier": 0.7
                },
                "deployment": {
                    "infra_workload_multiplier": 2.0,
                    "pm_workload_multiplier": 1.3
                }
            },
            
            # 项目复杂度调整
            "complexity_adjustments": {
                "low": {
                    "senior_ratio_multiplier": 0.8,
                    "tl_ratio_multiplier": 0.8
                },
                "medium": {
                    "senior_ratio_multiplier": 1.0,
                    "tl_ratio_multiplier": 1.0
                },
                "high": {
                    "senior_ratio_multiplier": 1.3,
                    "tl_ratio_multiplier": 1.2
                },
                "critical": {
                    "senior_ratio_multiplier": 1.5,
                    "tl_ratio_multiplier": 1.5,
                    "require_backup_resources": True
                }
            }
        },
        
        # 配比计算设置
        "calculation_settings": {
            "rounding_method": "ceil",  # 向上取整
            "min_resource_allocation": 0.1,  # 最小资源分配比例
            "allow_partial_allocation": True,  # 允许部分分配
            "priority_based_adjustment": True,  # 基于优先级调整
            "cost_optimization": False  # 成本优化模式
        }
    }


def get_all_default_configs() -> Dict[str, Dict[str, Any]]:
    """
    获取所有默认配置
    
    Returns:
        Dict[str, Dict[str, Any]]: 包含所有配置类型的字典
    """
    return {
        "main": get_default_main_config(),
        "validation": get_default_validation_config(),
        "tl_ratio": get_default_tl_ratio_config()
    }